import axios from "axios"
import Vue from "vue"
import qs from "querystring"
import { errorAlert } from "../utils/alert"
import store from "../store"
import router from "../router"


// 环境判断
if (process.env.NODE_ENV === 'development') {
    Vue.prototype.$pre = "http://localhost:3000"
} else {
    Vue.prototype.$pre = ""
}

// 请求拦截
axios.interceptors.request.use(config => {
    // 如果不是登录请求就添加请求头authorization
    if (config.url !== '/api/userlogin') {
        config.headers.authorization = store.getters.user_info.token ? store.getters.user_info.token : JSON.parse(sessionStorage.getItem('user_info')).token;
    }
    // 统一添加请求前缀
    config.url = Vue.prototype.$pre + config.url;

    return config
})

// 相应拦截
axios.interceptors.response.use(res => {
    console.group("本次请求地址：" + res.config.url)
    console.log(res);
    console.groupEnd()

    //统一处理失败
    if (res.data.code !== 200) {
        errorAlert(res.data.msg)
    }

    // 统一处理登录过期
    if (res.data.msg === "登录已过期或访问权限受限") {
        // 清除用户信息
        store.dispatch('set_userInfo', {});
        // 跳转登录页
        router.replace('/login')
    }

    return res
})

// 封装get
export const get = (url, params = {}) => {
    return axios({
        url,
        method: 'get',
        params
    })
};

// 封装post
export const post = (url, params = {}, haveFile = false) => {
    let data = null;
    // 判断是否文件传输
    if (haveFile) {
        data = new FormData;
        for (let key in params) {
            data.append(key, params[key])
        }
    } else {
        data = qs.stringify(params)
    }
    return axios({
        url,
        method: "post",
        data
    })
}